"""
File: base_api.py
Author: ershixiong
Date: 2023/12/12
describe:

"""
import json
import os

import requests
import yaml

from project202311_wework.wework.frame.utils.log_utils import logger
from project202311_wework.wework.frame.utils.utils import Utils


class BaseApi:
    def __init__(self):
        self.base_url = 'https://qyapi.weixin.qq.com/cgi-bin/'
        yaml_path = os.sep.join([Utils.get_root_dir(), 'config/secret.yaml'])

        yaml_data = Utils.get_yaml_data(yaml_path)
        corpid = yaml_data.get('corpid').get('lk')
        corpsecret = yaml_data.get('corpsecret').get('contact')

        from project202311_wework.wework.frame.apis.wework import Wework
        wework = Wework(corpid, corpsecret)
        self.access_token = wework.get_access_token(corpid, corpsecret)

    # 封装底层接口请求工具requests
    def send_api(self, req):
        """
        req = {
            'method': 'POST',
            'url': 'xxx',
            'params': 'xxx',
            'json': 'xxx'
        }
        :param req:
        :return:
        """

        # 判断params是否需要传入access_token以外的参数
        params = {'access_token': self.access_token}
        if req.get('params'):
            req['params'].update(params)
        else:
            req['params'] = params

        req['url'] = f'{self.base_url}{req["url"]}'

        logger.info(f'请求数据为{json.dumps(req, indent=2, ensure_ascii=False)}')
        r = requests.request(**req)
        logger.info(f'响应数据为{json.dumps(r.json(), indent=2, ensure_ascii=False)}')
        return r
